#############################################
#                                           #
#	Msn Interface for SlackAudit Framework  #
#			     Author: Plaix              #
#                                           #
#############################################

import msnlib
import msncb
import ModuleLoader
import select
import socket
import time
from time import strftime
import commands
import os
import random
import sys, traceback

class intMsn:
    link=None
    def __init__(self):
        #init msn object
        self.link=msnlib.msnd()
        self.link.cb=msncb.cb()
        
        #admin list, aanpassen voor toegang te geven tot admin commands
        self.adminlist=['semmyboyke@hotmail.com','wouterdetroyer@hotmail.com']
        self.adminlist=set(self.adminlist)

        #load modules
        self.moduleHook=ModuleLoader.ModuleLoader()
        self.moduleHook.loadModules()
	self.moduleHook.listModules()
        #get hostname from system
        self.hostname=self.moduleHook.useModule("modSysName#")
    def info(self):
        return "Msn Interface example By Plaix"
    def sendAlert(self,monitor,type,result):
        for i in self.link.users.keys():
            if self.link.users[i].status!="FLN":
                print "Sending alert to: "+self.link.users[i].email
                #TODO:loggen naar file of db
                self.link.sendmsg(self.link.users[i].email,self.hostname+" Monitor alert:\n")
                alert="Monitor "+monitor+" has raised a "+type+" alert\n Info: "+result
                self.link.sendmsg(self.link.users[i].email,alert)

    def getHelpList(self,email):
        list="Commands\n\
        !modules	list modules\n\
        !startm		start module\n"
        if(email in self.adminlist):
            list+="Admin commands:\n\
            !cmd	execute cmd, syntax !cmd#whatever command you want without #\n\
            !useradd	add user, syntax !useradd#john.doe@hotmail.com\
            !adminadd	add admin, syntax !adminadd#john.doe@hotmail.com\n\
            log commands:\n\
            !checkKippo	check Kippo honeypot logs for today\n\
            !checkAuth	check Auth logs for today\n\
            !checkNep	check Nepenthes logs for today\n"
            for line in self.moduleHook.listModules():
                list+=line+"\n"
            
            self.link.sendmsg(email,self.hostname+list)

#################ADMIN CMDS###################
#-----------------LOG VIEWS-------------------
    def executeCMD(self,email,cmd):
        #hier opletten voor exploiting met raw pakkets dus kan passwoord check
        if(email in self.adminlist):
            print "Executing command: "+cmd+"\n"
            self.link.sendmsg(email,self.hostname+commands.getoutput(cmd))
        else:
            self.link.sendmsg(email,"stop trying to hack the bot you tard!")

    def checkKippo(self,email):
        #cat /opt/kippo-0.4/log/kippo.log | grep "2010-05-27" | grep "login attempt" | cut -d " " -f1,2,6,9,10 | sed s/SSHServerTransport,.,// | sed s/]//
        if(email in self.adminlist):
            self.link.sendmsg(email,self.hostname+":Grabbing today's log of kippo: \n")
            result=commands.getoutput("cat /opt/kippo-0.4/log/kippo.log | grep \""+datenow+"\" | grep \"login attempt\" | cut -d \" \" -f1,2,6,9,10 | sed s/SSHServerTransport,.,// | sed s/]//")
            if(result!=""):
                self.link.sendmsg(email,result)
            else:
                self.link.sendmsg(email,"No new SSH connections today!\n")
                
    def checkAuth(self,email):
        #cat /var/log/auth.log | grep "27" | grep "session" | cut -d" " -f3,8,11 | sed /Agent/d | sort | uniq
        if(email in self.adminlist):
            self.link.sendmsg(email,self.hostname+":Grabbing today's log of auth: \n")
            result=commands.getoutput("cat /var/log/auth.log | grep \""+strftime("%d")+"\" | grep \"session\" | cut -d\" \" -f3,8,11 | sed /Agent/d |sort | uniq")
            if(result!=""):
                self.link.sendmsg(email,result)
            else:
                self.link.sendmsg(email,"No user activity today!\n")
                
    def checkNep(self,email):
        #cat /var/log/nepenthes.log | grep \""+strftime(%d%m%Y)+"\" | grep "submit] File" | cut -d \" \" -f1,2,7 | sort | uniq
        if(email in self.adminlist):
            self.link.sendmsg(email,self.hostname+":grabbing today's log of nepenthes: \n")
            result=commands.getoutput("cat /var/log/nepenthes.log | grep \""+strftime("%d%m%Y")+"\" | grep \"warn module\" | cut -d \" \" -f1,2,5-7 | sort | uniq")
            if(result!=""):
                self.link.sendmsg(email,result)
            else:
                self.link.sendmsg(email,"No new malware for today!\n")	
                
#---------------------------------------------
    def addNewUser(self,email,newuser):
        if(email in self.adminlist):
            self.link.useradd(newuser)
            self.link.sendmsg(email,"User added to global list!")
            
    def addNewAdmin(self,email,newuser):
        if(email in self.adminlist):
            self.link.sendmsg(email,"Not implemented yet! New admin would be: "+newuser)
            
    def say(self,email,dest,msg):
        if(email in self.adminlist):
            self.link.sendmsg(dest,msg)
            
    def sayAll(self,msg):
        for i in self.link.users.keys():
            if self.link.users[i].status!="FLN":
                self.link.sendmsg(self.link.users[i].email,msg)
                print "MSG send to :"+self.link.users[i].email + "\n"
                
    def cb_msg(self,md, type, tid, params, sbd):
        #parameters is effectieve tekst van message
        #md is msn connectie 
        #tid is userdatastring, splitten op " ", email_nick_nummerwhatever
        userdata=tid.split(" ")
        #debug('MESSAGE\n+++ Header: %s\n%s\n\n' % (str(tid), str(params)))

        if type!="MSG" or userdata[1]=="Hotmail" : 
            #hotmail dat shizzle doorstuurd van email,BOEIE
            return
        #email gemakkelijk maken
        email=userdata[0]
        #parsen die shizzle
        #hierdoor multiple commands in 1 bericht,worden 1 voor 1 uitgevoerd
        commands=params.split('\r\n')
        for line in commands:

            if(line=="!help"):
                self.getHelpList(email)
            elif(line=="!modules"):
                self.getModules(email)
            elif(line=="!testhack"):
                result="test hack"
                self.sendAlert(result)
            elif(line=="!checkKippo"):
                self.checkKippo(email)
            elif(line=="!checkAuth"):
                self.checkAuth(email)
            elif(line=="!checkNep"):
                self.checkNep(email)

            ###multiple arguments commands###
            elif(line.find("!cmd#") > -1):
                arg=line.split("#")
                self.executeCMD(email,arg[1])
            elif(line.find("!useradd#")>-1):
                arg=line.split("#")
                self.addNewUser(email,arg[1])
            elif(line.find("!adminadd#")>-1):
                arg=line.split("#")
                self.addNewAdmin(email,arg[1])
            elif(line.find("!say#")>-1):
                print "say command invoked!\n"
                arg=line.split("#")
                self.say(email,arg[1],arg[2])
            elif(line.find("!sayall#")>-1):
                arg=line.split("#")
                self.sayAll(arg[1])
            ###else parse it through to modules
            else:
                if(line.find("!")>-1):
                    self.link.sendmsg(email, self.moduleHook.useModule(line[1:]))
                
    def login(self,user,password):
        self.link.email=user
        self.link.pwd=password
        print "msn login called!\n"
        self.link.login()
        #get contact list and stuff
        self.link.sync()
        self.link.change_status("online")
        self.link.change_nick("Auditing For Slackers")
        #hook up our message handler
        self.link.cb.msg=self.cb_msg
        
    def	loop(self):
        #msn lib related stuff 
        t = self.link.pollable()
        infd = t[0]
        outfd = t[1]	
        #check the incomming messages
        try:
            fds = select.select(infd, outfd, [], 0)
        except:
            quit()

        for i in fds[0] + fds[1]:       # see msnlib.msnd.pollable.__doc__
            try:
                self.link.read(i)
            except:
                if i != self.link: 
                    self.link.close(i)
                else:
                    print "MSN ERROR: \n"
                    traceback.print_exc()
                    quit()
                    
    def alert(self,monitor,type,result):
        self.sendAlert(monitor,type,result)
